/*
 * @Author: tom
 * @Date: 2022-09-05 18:47:43
 * @LastEditors: 阿航
 * @LastEditTime: 2022-10-28 14:26:04
 * @FilePath: \shop\src\utils\request.js
 */
import axios from 'axios'
import {ElMessage} from 'element-plus'
import {getToken} from '../utils/auth'
// import {useRouter} from 'vue-router'
// import router from "router";
// const router = useRouter()
import router from '@/router'
const request = axios.create({
  baseURL: 'http://localhost:1337',
  timeout: 5000,
})

const token = localStorage.getItem('token')
request.interceptors.request.use(
  (config) => {
    config.headers.token = getToken()

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    const code = response.data.code
    if (code == 0) {
      ElMessage({
        type: 'error',
        message: response.data.data,
      })

      // router.push({
      //   path: '/login',
      // })
    }
    return response.data
  },
  (error) => {
    if (error.response?.status) {
      console.log(error.response?.status)
      if (error.response?.status == 401) {
        ElMessage({
          type: 'error',
          message: '没有登录',
        })
        router.push({
          path: '/login',
        })
      }
    }
  }
)

/**
 * get请求
 * @param {*} url     请求地址
 * @param {*} params  url中传递的参数
 * @returns
 */
export const get = (url, params) => request.get(url, {params})

/**
 * 发起post请求
 * @param {*} url   请求地址
 * @param {*} data  传递的数据
 * @returns
 */
export const post = (url, data) => request.post(url, data)

/**
 * 发起put请求
 * @param {*} url   请求地址
 * @param {*} data  数据
 * @returns
 */
export const put = (url, data) => request.put(url, data)

/**
 * 发起delete请求
 * @param {*} url 请求地址
 * @returns
 */
export const del = (url) => request.delete(url)

// 默认导出
export default request
